//
//  ASTool.m
//  FoodEnum
//
//  Created by xunruiIOS on 2020/7/20.
//  Copyright © 2020 xunruiIos. All rights reserved.
//

#import "ASTool.h"
#import "sys/utsname.h"
#import "SDImageCache.h"
@implementation ASTool

/**
获取与服务端时间同步后的本地时间
*/
+ (NSInteger)createLoadNetTime{
    NSDate * date = [NSDate date];

    NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];

    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

    //设置时间间隔（秒）（这个我是计算出来的，不知道有没有简便的方法 )

//    NSTimeInterval time = 365 * 24 * 60 * 60;//一年的秒数
    NSNumber *num = [[NSUserDefaults standardUserDefaults]objectForKey:TIME_INTERVAL];
    NSTimeInterval time = num.integerValue;

    //得到一年之前的当前时间（-：表示向前的时间间隔（即去年），如果没有，则表示向后的时间间隔（即明年））

    NSDate * lastYear = [date dateByAddingTimeInterval:-time];

    //转化为字符串
    NSString * startDate = [dateFormatter stringFromDate:lastYear];

    return [[self class]timeSwitchTimestamp:startDate andFormatter:@"yyyy-MM-dd HH:mm:ss"];
}

//数组中的随机色值
+ (UIColor *)backgroundRandomColor{
    NSArray *colorArr = @[@"#ffeaec",@"#fbd3e0",@"#ebd5f0",@"#e2d9f0",@"#d9dcf0",@"#d3eafc",@"#ceeefd",@"#cdf2f7",@"#cdeae8",@"#dbefdc",@"#e9f3db",@"#f5f8d7",@"#fdf5d2",@"#ffebcc",@"#ffddd2",@"#eeeeee",@"#e0e6e9",@"#e5dedb"];
    int value = arc4random() % colorArr.count;
    NSString *colorStr = [colorArr objectAtIndex:value];
    return [UIColor colorWithHexString:colorStr];
}

/**
 将某个时间转化成 时间戳
 */
+ (NSInteger)timeSwitchTimestamp:(NSString *)formatTime andFormatter:(NSString *)format{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    [formatter setDateFormat:format]; //(@"YYYY-MM-dd HH:mm:ss") ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    
    [formatter setTimeZone:timeZone];
    
    NSDate* date = [formatter dateFromString:formatTime]; //------------将字符串按formatter转成nsdate
    
    //时间转时间戳的方法:
    
    NSInteger timeSp = [[NSNumber numberWithDouble:[date timeIntervalSince1970]] integerValue];
        
    return timeSp;
}

/// 获取系统当前时间
/// @param formatStr YYYY-MM-dd HH:mm:ss
+(NSString*)getCurrentTimesFormat:(NSString *)formatStr {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:formatStr];
    NSDate *dateNow = [NSDate date];
    NSString *currentTime = [formatter stringFromDate:dateNow];
    return currentTime;
}

/**
 计算两个时间戳相差多少分钟  2020-04-14 21:46:48   2020-04-14 14:26:01
*/
+ (int)compareTwoTime:(NSInteger)time1 time2:(NSInteger)time2{
    //    1602622351
//    1602621388
    NSTimeInterval balance = time2 /1000- time1 /1000;
    if (time2 > time1) {
        balance = time2 /1000- time1 /1000;
    }else{
        balance = time1 /1000- time2 /1000;
    }
    NSString*timeString = [[NSString alloc]init];
    timeString = [NSString stringWithFormat:@"%f",balance /60];
    timeString = [timeString substringToIndex:timeString.length-7];
    int timeInt = [timeString intValue];
    return timeInt;
}

/**
 2  * @method
 3  *
 4  * @brief 获取两个日期之间分钟
 5  * @param fromDate       起始日期
 6  * @param toDate         终止日期
 7  * @return    总分钟
 8  */
+ (NSInteger)numberOfDaysWithFromDate:(NSDate *)fromDate toDate:(NSDate *)toDate{
    NSCalendar *cal=[NSCalendar currentCalendar];
    unsigned int unitFlags= NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute;
    NSDateComponents *comp = [cal components:unitFlags fromDate:fromDate toDate:toDate options:0];
    NSInteger hor = comp.day * 24;
    NSInteger minHor = hor + comp.hour;
    NSInteger min = (minHor * 60) + comp.minute;
    return min;
}


/// 返回一个颜色渐变图片
/// @param startColor 开始色
/// @param endColor 结束的颜色
/// @param ifVertical 是否纵向渐变
+(UIImage *)colorGradientWithStartColor:(UIColor *)startColor endColor:(UIColor *)endColor ifVertical:(BOOL)ifVertical imageSize:(CGSize)imageSize{
    CGSize size = imageSize;
    UIImage *bgImage;
    UIGraphicsBeginImageContextWithOptions(size, YES, 1.0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.frame = CGRectMake(0, 0, imageSize.width, imageSize.height);
    gradientLayer.startPoint = CGPointMake(0, 0);
    gradientLayer.endPoint = CGPointMake(0, 1);
    if (ifVertical) {
        gradientLayer.endPoint = CGPointMake(0, 1);
    }
    gradientLayer.locations = @[@(1),@(0.0)];//渐变点
    [gradientLayer setColors:@[(id)startColor.CGColor,(id)endColor.CGColor]];
    [gradientLayer renderInContext:context];
    bgImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return bgImage;
}

/// 计算lab的行数
/// @param text text
/// @param font 字体
/// @param width 宽度
+(NSArray *)getSeparatedLinesFromLabelText:(NSString *)text font:(UIFont *)font width:(CGFloat)width{
    CTFontRef myFont = CTFontCreateWithName((__bridge CFStringRef)([font fontName]), [font pointSize], NULL);
    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:text];
    [attStr addAttribute:(NSString *)kCTFontAttributeName value:(__bridge id)myFont range:NSMakeRange(0, attStr.length)];
    CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)attStr);
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddRect(path, NULL, CGRectMake(0,0,width,100000));
    CTFrameRef frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, NULL);
    NSArray *lines = (__bridge NSArray *)CTFrameGetLines(frame);
    NSMutableArray *linesArray = [[NSMutableArray alloc]init];
    for (id line in lines){
        CTLineRef lineRef = (__bridge CTLineRef )line;
        CFRange lineRange = CTLineGetStringRange(lineRef);
        NSRange range = NSMakeRange(lineRange.location, lineRange.length);
        NSString *lineString = [text substringWithRange:range];
        [linesArray addObject:lineString];
    }
    return (NSArray *)linesArray;
}

/**
 根据高度求宽度
 @param text 计算的内容
 @param height 计算的高度
 @param font font字体大小
 @return 返回Label的宽度
 */
+ (CGFloat)getWidthWithText:(NSString *)text height:(CGFloat)height font:(CGFloat)font{
    CGRect rect = [text boundingRectWithSize:CGSizeMake(MAXFLOAT, height)
                   options:NSStringDrawingUsesLineFragmentOrigin
                   attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:font]}
                   context:nil];

    return rect.size.width;
}

/**
 根据宽度度求高度
 @param text 计算的内容
 @param width 计算的宽度
 @param font font字体大小
 @return 返回Label的宽度
 */
+ (CGFloat)getHeightWithText:(NSString *)text width:(CGFloat)width font:(UIFont *)font{
    CGRect rect = [text boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX)
                   options:NSStringDrawingUsesLineFragmentOrigin
                   attributes:@{NSFontAttributeName:font}
                   context:nil];

    return rect.size.height;
}

/**
 计算文本高度
 
 @param str         文本内容
 @param width       lab宽度
 @param lineSpacing 行间距(没有行间距就传0)
 @param font        文本字体大小
 
 @return 文本高度
 */
+(CGFloat)getTextHeightWithStr:(NSString *)str
                     withWidth:(CGFloat)width
               withLineSpacing:(CGFloat)lineSpacing
                      withFont:(CGFloat)font
{
    NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
    paraStyle.lineBreakMode = NSLineBreakByCharWrapping;
    paraStyle.alignment = NSTextAlignmentLeft;
    paraStyle.lineSpacing = lineSpacing;
    paraStyle.hyphenationFactor = 1.0;
    paraStyle.paragraphSpacingBefore = 0.0;
    paraStyle.firstLineHeadIndent = 0.0;
    paraStyle.headIndent = 0;
    paraStyle.tailIndent = 0;
    NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:font], NSParagraphStyleAttributeName:paraStyle, NSKernAttributeName:@1.5f};
    CGSize size = [str boundingRectWithSize:CGSizeMake(width, 10000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil].size;
    return size.height;
}

/// 改变一个lab的行间距
/// @param label label description
/// @param space space description
+ (void)changeLineSpaceForLabel:(UILabel *)label WithSpace:(float)space {
    NSString *labelText = label.text;
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:labelText];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:space];
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [labelText length])];
    label.attributedText = attributedString;
    [label sizeToFit];

}

//设置viwe锚点
+ (void)hf_setAnchorPoint:(CGPoint)anchorPoint supView:(UIView *)subV{
    CGPoint newPoint = CGPointMake(subV.bounds.size.width * anchorPoint.x, subV.bounds.size.height * anchorPoint.y);
    CGPoint oldPoint = CGPointMake(subV.bounds.size.width * subV.layer.anchorPoint.x, subV.bounds.size.height * subV.layer.anchorPoint.y);
    
    newPoint = CGPointApplyAffineTransform(newPoint, subV.transform);
    oldPoint = CGPointApplyAffineTransform(oldPoint, subV.transform);
    
    CGPoint position = subV.layer.position;
    position.x -= oldPoint.x;
    position.x += newPoint.x;
    position.y -= oldPoint.y;
    position.y += newPoint.y;
    
    subV.layer.position = position;
    subV.layer.anchorPoint = anchorPoint;
}

/*
 自定义方法：获取缓存大小
 由于缓存文件存在沙箱中，我们可以通过NSFileManager API来实现对缓存文件大小的计算。
 遍历文件夹获得文件夹大小，返回多少 M
 */
+ (float) getCacheSize{
    return [[self class] filePath];
}

// 清除缓存
+ (void)clearFile{
    [self clearCache];
}

// 计算 单个文件的大小
+ ( long long ) fileSizeAtPath:( NSString *) filePath{
    NSFileManager * manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath :filePath]){
        return [[manager attributesOfItemAtPath :filePath error : nil] fileSize];
    }
    return 0;
}

+ (float)filePath {
    NSString * cachPath = [ NSSearchPathForDirectoriesInDomains ( NSCachesDirectory , NSUserDomainMask , YES ) firstObject ];
    return [[self class] folderSizeAtPath:cachPath];
}

//遍历文件夹获得文件夹大小，返回多少M
+ (float )folderSizeAtPath:(NSString*) folderPath {
    long long totalSize = 0;

//    //1.获取“cachePath”文件夹下面的所有文件
//    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
//    NSArray *subpathArray= [[NSFileManager defaultManager] subpathsAtPath:cachePath];
//    NSString *filePath = nil;
//    for (NSString *subpath in subpathArray) {
//        // 拼接每一个文件的全路径
//        filePath =[cachePath stringByAppendingPathComponent:subpath];
//        BOOL isDirectory = NO;   //是否文件夹，默认不是
//        BOOL isExist = [[NSFileManager defaultManager] fileExistsAtPath:filePath isDirectory:&isDirectory];   // 判断文件是否存在
//        // 文件不存在,是文件夹,是隐藏文件都过滤
//        if (!isExist || isDirectory || [filePath containsString:@".DS"]) continue;
//        // attributesOfItemAtPath 只可以获得文件属性，不可以获得文件夹属性，
//        //这个也就是需要遍历文件夹里面每一个文件的原因
//        long long fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil] fileSize];
//        totalSize += fileSize;
//    }

    //SDWebImage框架自身计算缓存的实现
    NSInteger webSize =  [[YYImageCache sharedCache].diskCache totalCost];;
    NSInteger sdSize =  [SDImageCache sharedImageCache].totalDiskSize;
    if (webSize < 10) {
        webSize = 10;
    }
    totalSize += webSize;
    totalSize += sdSize;
    return totalSize/(1024.0*1024.0);
}

///清除缓存
+ (void)clearCache {
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSArray *subpathArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:cachePath error:nil];
    NSError *error = nil;
    NSString *filePath = nil;
    BOOL flag = NO;
    for (NSString *subpath in subpathArray) {
        filePath = [cachePath stringByAppendingPathComponent:subpath];
        if ([[NSFileManager defaultManager] fileExistsAtPath:cachePath]) {
            
            // 删除子文件夹
            BOOL isRemoveSuccessed = [[NSFileManager defaultManager] removeItemAtPath:filePath error:&error];
            if (isRemoveSuccessed) { // 删除成功
                flag = YES;
            }
        }
    }
    [[YYImageCache sharedCache].diskCache removeAllObjects];
    [[SDImageCache sharedImageCache]clearDiskOnCompletion:nil];
}


/// 获取app版本号
+ (NSString *)versionNumber{
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    return app_Version;
}

/**
 *  手机型号
 *
 *  @return e.g. iPhone  https://www.theiphonewiki.com/wiki/Models  设备参考资料
 */
+(NSString *)phoneModel{
  // 需要#import "sys/utsname.h"
     struct utsname systemInfo;
     uname(&systemInfo);
     NSString *deviceString = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
     
     //iPhone
     if ([deviceString isEqualToString:@"iPhone1,1"])    return @"iPhone 1G";
     if ([deviceString isEqualToString:@"iPhone1,2"])    return @"iPhone 3G";
     if ([deviceString isEqualToString:@"iPhone2,1"])    return @"iPhone 3GS";
     if ([deviceString isEqualToString:@"iPhone3,1"])    return @"iPhone 4";
     if ([deviceString isEqualToString:@"iPhone3,2"])    return @"Verizon iPhone 4";
     if ([deviceString isEqualToString:@"iPhone4,1"])    return @"iPhone 4S";
     if ([deviceString isEqualToString:@"iPhone5,1"])    return @"iPhone 5";
     if ([deviceString isEqualToString:@"iPhone5,2"])    return @"iPhone 5";
     if ([deviceString isEqualToString:@"iPhone5,3"])    return @"iPhone 5C";
     if ([deviceString isEqualToString:@"iPhone5,4"])    return @"iPhone 5C";
     if ([deviceString isEqualToString:@"iPhone6,1"])    return @"iPhone 5S";
     if ([deviceString isEqualToString:@"iPhone6,2"])    return @"iPhone 5S";
     if ([deviceString isEqualToString:@"iPhone7,1"])    return @"iPhone 6 Plus";
     if ([deviceString isEqualToString:@"iPhone7,2"])    return @"iPhone 6";
     if ([deviceString isEqualToString:@"iPhone8,1"])    return @"iPhone 6s";
     if ([deviceString isEqualToString:@"iPhone8,2"])    return @"iPhone 6s Plus";
     if ([deviceString isEqualToString:@"iPhone8,4"])    return @"iPhone SE";
     if ([deviceString isEqualToString:@"iPhone9,1"])    return @"iPhone 7";
     if ([deviceString isEqualToString:@"iPhone9,3"])    return @"iPhone 7";
     if ([deviceString isEqualToString:@"iPhone9,2"])    return @"iPhone 7 Plus";
     if ([deviceString isEqualToString:@"iPhone9,4"])    return @"iPhone 7 Plus";
     if ([deviceString isEqualToString:@"iPhone10,1"])    return @"iPhone 8";
     if ([deviceString isEqualToString:@"iPhone10,4"])    return @"iPhone 8";
     if ([deviceString isEqualToString:@"iPhone10,2"])    return @"iPhone 8 Plus";
     if ([deviceString isEqualToString:@"iPhone10,5"])    return @"iPhone 8 Plus";
     if ([deviceString isEqualToString:@"iPhone10,3"])    return @"iPhone X";
     if ([deviceString isEqualToString:@"iPhone10,6"])    return @"iPhone X";
     if ([deviceString isEqualToString:@"iPhone11,8"])    return @"iPhone XR";
     if ([deviceString isEqualToString:@"iPhone11,2"])    return @"iPhone XS";
     if ([deviceString isEqualToString:@"iPhone11,6"])    return @"iPhone XS Max";
     if ([deviceString isEqualToString:@"iPhone12,1"])    return @"iPhone 11";
     if ([deviceString isEqualToString:@"iPhone12,3"])    return @"iPhone 11 Pro";
     if ([deviceString isEqualToString:@"iPhone12,5"])    return @"iPhone 11 ProMax";
     if ([deviceString isEqualToString:@"iPhone13,1"])    return @"iPhone 12";
     if ([deviceString isEqualToString:@"iPhone13,3"])    return @"iPhone 12 Pro";


     //iPod
     if ([deviceString isEqualToString:@"iPod1,1"])      return @"iPod Touch 1G";
     if ([deviceString isEqualToString:@"iPod2,1"])      return @"iPod Touch 2G";
     if ([deviceString isEqualToString:@"iPod3,1"])      return @"iPod Touch 3G";
     if ([deviceString isEqualToString:@"iPod4,1"])      return @"iPod Touch 4G";
     if ([deviceString isEqualToString:@"iPod5,1"])      return @"iPod Touch 5G";
     
     //iPad
     if ([deviceString isEqualToString:@"iPad1,1"])      return @"iPad";
     if ([deviceString isEqualToString:@"iPad2,1"])      return @"iPad 2 (WiFi)";
     if ([deviceString isEqualToString:@"iPad2,2"])      return @"iPad 2 (GSM)";
     if ([deviceString isEqualToString:@"iPad2,3"])      return @"iPad 2 (CDMA)";
     if ([deviceString isEqualToString:@"iPad2,4"])      return @"iPad 2 (32nm)";
     if ([deviceString isEqualToString:@"iPad2,5"])      return @"iPad mini (WiFi)";
     if ([deviceString isEqualToString:@"iPad2,6"])      return @"iPad mini (GSM)";
     if ([deviceString isEqualToString:@"iPad2,7"])      return @"iPad mini (CDMA)";
     
     if ([deviceString isEqualToString:@"iPad3,1"])      return @"iPad 3(WiFi)";
     if ([deviceString isEqualToString:@"iPad3,2"])      return @"iPad 3(CDMA)";
     if ([deviceString isEqualToString:@"iPad3,3"])      return @"iPad 3(4G)";
     if ([deviceString isEqualToString:@"iPad3,4"])      return @"iPad 4 (WiFi)";
     if ([deviceString isEqualToString:@"iPad3,5"])      return @"iPad 4 (4G)";
     if ([deviceString isEqualToString:@"iPad3,6"])      return @"iPad 4 (CDMA)";
     
     if ([deviceString isEqualToString:@"iPad4,1"])      return @"iPad Air";
     if ([deviceString isEqualToString:@"iPad4,2"])      return @"iPad Air";
     if ([deviceString isEqualToString:@"iPad4,3"])      return @"iPad Air";
     if ([deviceString isEqualToString:@"iPad5,3"])      return @"iPad Air 2";
     if ([deviceString isEqualToString:@"iPad5,4"])      return @"iPad Air 2";
     if ([deviceString isEqualToString:@"i386"])         return @"Simulator";
     if ([deviceString isEqualToString:@"x86_64"])       return @"Simulator";
     
     if ([deviceString isEqualToString:@"iPad4,4"]
         ||[deviceString isEqualToString:@"iPad4,5"]
         ||[deviceString isEqualToString:@"iPad4,6"])      return @"iPad mini 2";
     
     if ([deviceString isEqualToString:@"iPad4,7"]
         ||[deviceString isEqualToString:@"iPad4,8"]
         ||[deviceString isEqualToString:@"iPad4,9"])      return @"iPad mini 3";
     
     return deviceString;

}

/**
*  获取设备网络状态
*/
+ (NSString *)networkingStatesFromStatebar {
  UIApplication *app = [UIApplication sharedApplication];
        id statusBar = nil;
    //    判断是否是iOS 13
        NSString *network = @"";
        if (@available(iOS 13.0, *)) {
            UIStatusBarManager *statusBarManager = [UIApplication sharedApplication].keyWindow.windowScene.statusBarManager;
            
    #pragma clang diagnostic push
    #pragma clang diagnostic ignored "-Wundeclared-selector"
            if ([statusBarManager respondsToSelector:@selector(createLocalStatusBar)]) {
                UIView *localStatusBar = [statusBarManager performSelector:@selector(createLocalStatusBar)];
                if ([localStatusBar respondsToSelector:@selector(statusBar)]) {
                    statusBar = [localStatusBar performSelector:@selector(statusBar)];
                }
            }
    #pragma clang diagnostic pop
            if (statusBar) {
                id currentData = [[statusBar valueForKeyPath:@"_statusBar"] valueForKeyPath:@"currentData"];
                id _wifiEntry = [currentData valueForKeyPath:@"wifiEntry"];
                id _cellularEntry = [currentData valueForKeyPath:@"cellularEntry"];
                if (_wifiEntry && [[_wifiEntry valueForKeyPath:@"isEnabled"] boolValue]) {
    //              If wifiEntry is enabled, is WiFi.
                    network = @"WIFI";
                } else if (_cellularEntry && [[_cellularEntry valueForKeyPath:@"isEnabled"] boolValue]) {
                    NSNumber *type = [_cellularEntry valueForKeyPath:@"type"];
                    if (type) {
                        switch (type.integerValue) {
                            case 0:
    //                            无sim卡
                                network = @"NONE";
                                break;
                            case 1:
                                network = @"1G";
                                break;
                            case 4:
                                network = @"3G";
                                break;
                            case 5:
                                network = @"4G";
                                break;
                            default:
    //                            默认WWAN类型
                                network = @"WWAN";
                                break;
                                }
                            }
                        }
                    }
        }else {
            statusBar = [app valueForKeyPath:@"statusBar"];
            
            if (IS_IPHONE_X_MAIN) {
    //            刘海屏
                    id statusBarView = [statusBar valueForKeyPath:@"statusBar"];
                    UIView *foregroundView = [statusBarView valueForKeyPath:@"foregroundView"];
                    NSArray *subviews = [[foregroundView subviews][2] subviews];
                    
                    if (subviews.count == 0) {
    //                    iOS 12
                        id currentData = [statusBarView valueForKeyPath:@"currentData"];
                        id wifiEntry = [currentData valueForKey:@"wifiEntry"];
                        if ([[wifiEntry valueForKey:@"_enabled"] boolValue]) {
                            network = @"WIFI";
                        }else {
    //                    卡1:
                            id cellularEntry = [currentData valueForKey:@"cellularEntry"];
    //                    卡2:
                            id secondaryCellularEntry = [currentData valueForKey:@"secondaryCellularEntry"];

                            if (([[cellularEntry valueForKey:@"_enabled"] boolValue]|[[secondaryCellularEntry valueForKey:@"_enabled"] boolValue]) == NO) {
    //                            无卡情况
                                network = @"NONE";
                            }else {
    //                            判断卡1还是卡2
                                BOOL isCardOne = [[cellularEntry valueForKey:@"_enabled"] boolValue];
                                int networkType = isCardOne ? [[cellularEntry valueForKey:@"type"] intValue] : [[secondaryCellularEntry valueForKey:@"type"] intValue];
                                switch (networkType) {
                                        case 0://无服务
                                        network = [NSString stringWithFormat:@"%@-%@", isCardOne ? @"Card 1" : @"Card 2", @"NONE"];
                                        break;
                                        case 3:
                                        network = [NSString stringWithFormat:@"%@-%@", isCardOne ? @"Card 1" : @"Card 2", @"2G/E"];
                                        break;
                                        case 4:
                                        network = [NSString stringWithFormat:@"%@-%@", isCardOne ? @"Card 1" : @"Card 2", @"3G"];
                                        break;
                                        case 5:
                                        network = [NSString stringWithFormat:@"%@-%@", isCardOne ? @"Card 1" : @"Card 2", @"4G"];
                                        break;
                                    default:
                                        break;
                                }
                                
                            }
                        }
                    
                    }else {
                        
                        for (id subview in subviews) {
                            if ([subview isKindOfClass:NSClassFromString(@"_UIStatusBarWifiSignalView")]) {
                                network = @"WIFI";
                            }else if ([subview isKindOfClass:NSClassFromString(@"_UIStatusBarStringView")]) {
                                network = [subview valueForKeyPath:@"originalText"];
                            }
                        }
                    }
                    
                }else {
    //                非刘海屏
                    UIView *foregroundView = [statusBar valueForKeyPath:@"foregroundView"];
                    NSArray *subviews = [foregroundView subviews];
                    
                    for (id subview in subviews) {
                        if ([subview isKindOfClass:NSClassFromString(@"UIStatusBarDataNetworkItemView")]) {
                            int networkType = [[subview valueForKeyPath:@"dataNetworkType"] intValue];
                            switch (networkType) {
                                case 0:
                                    network = @"NONE";
                                    break;
                                case 1:
                                    network = @"2G";
                                    break;
                                case 2:
                                    network = @"3G";
                                    break;
                                case 3:
                                    network = @"4G";
                                    break;
                                case 5:
                                    network = @"WIFI";
                                    break;
                                default:
                                    break;
                            }
                        }
                    }
                }
        }

        if ([network isEqualToString:@""]) {
            network = @"NO DISPLAY";
        }
        return network;
}


/**
 *  手机系统版本
 *
 *  @return e.g. 8.0
 */
+(NSString *)phoneVersion{
    return [[UIDevice currentDevice] systemVersion];
}

/**
*  获取设备标示UUDI
*/
+(NSString *)phoneUUID{
    return [[UIDevice currentDevice] identifierForVendor].UUIDString;
}

/// 网络是否是wifi
+(BOOL)netWorkIsWifi{
    NSString *str = [[self class]networkingStatesFromStatebar];
    if ([str isEqualToString:@"WIFI"]) {
        return YES;
    }
    return NO;
}

//改变按钮的布局样式
+ (void)changeBtnStyleWithType:(FEBtnImageTitleType)type distance:(CGFloat)distance andBtn:(UIButton *)btn{
    if (type == FEBtnImageTitleType_ImageTop) {                 //图片上文字下
        btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
        CGFloat totalHeight = (btn.imageView.frame.size.height + btn.titleLabel.frame.size.height);
        [btn setImageEdgeInsets:UIEdgeInsetsMake(-(totalHeight - btn.imageView.frame.size.height), 0, 5, -btn.imageView.frame.size.width-btn.titleLabel.frame.size.width/2+6)];
        [btn setTitleEdgeInsets:UIEdgeInsetsMake((totalHeight - btn.titleLabel.frame.size.height)+distance, -btn.imageView.frame.size.width, 0,0.0)];
    }else if (type == FEBtnImageTitleType_ImagRight){            //图片又文字左
        CGFloat labelWidth = btn.titleLabel.intrinsicContentSize.width;
        CGFloat imageWidth = btn.imageView.frame.size.width;
        CGFloat space = distance; //定义两个元素交换后的间距
        btn.titleEdgeInsets = UIEdgeInsetsMake(0, - imageWidth - space,0,imageWidth + space);
        btn.imageEdgeInsets = UIEdgeInsetsMake(2, labelWidth + space, 0,  -labelWidth - space);
    }
}

//设置图片高斯模糊
+ (UIImage *)tg_blurryImage:(UIImage *)image withBlurLevel:(CGFloat)blur {
    if (image == nil) {
        return nil;
    }
    CIContext *context = [CIContext contextWithOptions:nil];
    CIImage *ciImage = [CIImage imageWithCGImage:image.CGImage];
    CIFilter *filter = [CIFilter filterWithName:@"CIGaussianBlur"];
    [filter setValue:ciImage forKey:kCIInputImageKey];
    //设置模糊程度
    [filter setValue:@(blur) forKey: @"inputRadius"];
    CIImage *result = [filter valueForKey:kCIOutputImageKey];
    CGImageRef outImage = [context createCGImage: result fromRect:ciImage.extent];
    UIImage * blurImage = [UIImage imageWithCGImage:outImage];
    CGImageRelease(outImage);
    return blurImage;
}

//获取 bundle version版本号
+(NSString*) getLocalAppVersion{
    return [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
}

//获取BundleID
+(NSString*) getBundleID{
    return [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleIdentifier"];
}

// 获取app的名字
+(NSString*) getAppName{
    NSString *appName = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"];
    NSMutableString *mutableAppName = [NSMutableString stringWithString:appName];
    return mutableAppName;
}


/** 获取scrollView的长截图*/
+ (UIImage *)getLongImage:(UITableView *)tableView
{
//    [tableView removeFromSuperview];
    tableView.frame = CGRectMake(0, 0, tableView.contentSize.width, tableView.contentSize.height);
    UIImage* image = [[UIImage alloc]init];
   // 下面方法，第一个参数表示区域大小。第二个参数表示是否是非透明的。如果需要显示半透明效果，需要传NO，否则传YES。第三个参数就是屏幕密度了，调整清晰度。
    UIGraphicsBeginImageContextWithOptions(tableView.contentSize, YES, [UIScreen mainScreen].scale);
    tableView.contentOffset = CGPointZero;
    [tableView.layer renderInContext: UIGraphicsGetCurrentContext()];
    tableView.layer.contents = nil;//释放
    image =UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

///随机字符串 - 生成指定长度的字符串
+(NSString *)randomStringWithLength:(NSInteger)len {
     NSString *letters = @"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    NSMutableString *randomString = [NSMutableString stringWithCapacity: len];
    
    for (NSInteger i = 0; i < len; i++) {
        [randomString appendFormat: @"%C", [letters characterAtIndex: arc4random_uniform([letters length])]];
    }
    return randomString;
}

/// 压缩图片
+(UIImage *)zipNSDataWithImage:(UIImage *)sourceImage{
    //进行图像尺寸的压缩
    CGSize imageSize = sourceImage.size;//取出要压缩的image尺寸
    CGFloat width = imageSize.width;    //图片宽度
    CGFloat height = imageSize.height;  //图片高度
    //1.宽高大于1280(宽高比不按照2来算，按照1来算)
    if (width>1280) {
        if (width>height) {
            CGFloat scale = width/height;
            height = 1280;
            width = height*scale;
        }else{
            CGFloat scale = height/width;
            width = 1280;
            height = width*scale;
        }
        //2.高度大于1280
    }else if(height>1280){
        CGFloat scale = height/width;
        width = 1280;
        height = width*scale;
    }else{
    }
    UIGraphicsBeginImageContext(CGSizeMake(width, height));
    [sourceImage drawInRect:CGRectMake(0,0,width,height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    //进行图像的画面质量压缩
    NSData *data=UIImageJPEGRepresentation(newImage, 1.0);
    if (data.length>100*1024) {
        if (data.length>1024*1024) {//1M以及以上
            data=UIImageJPEGRepresentation(newImage, 0.7);
        }else if (data.length>512*1024) {//0.5M-1M
            data=UIImageJPEGRepresentation(newImage, 0.8);
        }else if (data.length>200*1024) {
            //0.25M-0.5M
            data=UIImageJPEGRepresentation(newImage, 0.9);
        }
    }
    
    UIImage *changeImage = [UIImage imageWithData:data];
    return changeImage;
}

/// 视频压缩后存储的路径
+ (NSString *)creatSandBoxFilePathIfNoExist
{
    //沙盒路径
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDirectory = [paths objectAtIndex:0];
    NSLog(@"databse--->%@",documentDirectory);
    
    NSFileManager *fileManager = [[NSFileManager alloc] init];
    NSString *pathDocuments = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    
    NSDateFormatter *formater = [[NSDateFormatter alloc] init];// 用时间, 给文件重新命名, 防止视频存储覆盖,
    [formater setDateFormat:@"yyyy-MM-dd-HH:mm:ss"];
    //创建目录
    NSString *createPath = [NSString stringWithFormat:@"%@/Video", pathDocuments];
    // 判断文件夹是否存在，如果不存在，则创建
    if (![[NSFileManager defaultManager] fileExistsAtPath:createPath]) {
        [fileManager createDirectoryAtPath:createPath withIntermediateDirectories:YES attributes:nil error:nil];
    } else {
        NSLog(@"FileImage is exists.");
    }
    
    NSString *resultPath = [createPath stringByAppendingPathComponent:[NSString stringWithFormat:@"outputJFVideo-%@.mov",[formater stringFromDate:[NSDate date]]]];
    NSLog(@"%@",resultPath);
    return resultPath;
}

/**
 获取视频略缩图
 */
+ (UIImage *)imageURL:(PHAsset *)phAsset targetSize:(CGSize)targetSize {
    __block UIImage *image = nil;
    
    PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    PHImageManager *manager = [PHImageManager defaultManager];
    options.resizeMode = PHImageRequestOptionsResizeModeExact;
    options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
    options.normalizedCropRect = CGRectMake(0, 0, targetSize.width, targetSize.height);
    
    [manager requestImageForAsset:phAsset targetSize:targetSize contentMode:PHImageContentModeAspectFill options:options resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
        image = result;
        dispatch_semaphore_signal(semaphore);
    }];
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    return image;
}

///删除指定地址目录下的文件
+ (void)removeDocumentWithFilePath:(NSString*)filePath{
    NSString* cachePath = filePath;
    if ([filePath containsString:@"file://"]) {
        cachePath = [filePath stringByReplacingOccurrencesOfString:@"file://" withString:@""];
    }
    NSFileManager*fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:cachePath]) {
       BOOL bo = [fileManager removeItemAtPath:cachePath error:NULL];
        FELog(@"dfdfdfdf===%d",bo);
    }
}

///根据颜色生成一张图片
+(UIImage*)createImageWithColor:(UIColor*) color
{
    CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}


/*
    txt:label或button的title
    font:字体大小
    size:允许最大size
 */
+(CGSize)boundingRectWithSize:(NSString*)txt Font:(UIFont*) font Size:(CGSize)size{
    
    CGSize _size;
    
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_6_1
    
    NSDictionary *attribute = @{NSFontAttributeName: font};
    
    NSStringDrawingOptions options = NSStringDrawingTruncatesLastVisibleLine |
    
    NSStringDrawingUsesLineFragmentOrigin |
    
    NSStringDrawingUsesFontLeading;
    
    _size = [txt boundingRectWithSize:size options: options attributes:attribute context:nil].size;
    
#else
    
    _size = [txt sizeWithFont:font constrainedToSize:size];
    
#endif
    
    return _size;
    
}

///计算lab高度
+ (CGFloat)getterSpaceLabelHeight:(NSString*)string withLineSpacing:(CGFloat)lineSpacing withFont:(UIFont*)font withWidth:(CGFloat)width{
    NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
    paraStyle.lineBreakMode = NSLineBreakByCharWrapping;
    paraStyle.alignment = NSTextAlignmentLeft;
    paraStyle.lineSpacing = lineSpacing;
    paraStyle.hyphenationFactor = 1.0;
    paraStyle.firstLineHeadIndent = 0.0;
    paraStyle.paragraphSpacingBefore = 0.0;
    paraStyle.headIndent = 0;
    paraStyle.tailIndent = 0;
    NSDictionary *dic =@{NSFontAttributeName:font,NSParagraphStyleAttributeName:paraStyle,NSKernAttributeName:@1.0f
                         };
    
    CGSize size = [string boundingRectWithSize:CGSizeMake(width,MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil].size;
    return size.height;
    
    
}

///压缩图片
+ (UIImage *)compressImage:(UIImage *)image toByte:(NSUInteger)maxLength {
    UIImage *resultImage = image;
    NSData *data = UIImageJPEGRepresentation(resultImage, 1);
    NSUInteger lastDataLength = 0;
    while (data.length > maxLength && data.length != lastDataLength) {
        lastDataLength = data.length;
        CGFloat ratio = (CGFloat)maxLength / data.length;
        CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(ratio)),
                                 (NSUInteger)(resultImage.size.height * sqrtf(ratio))); // Use NSUInteger to prevent white blank
        UIGraphicsBeginImageContext(size);
        // Use image to draw (drawInRect:), image is larger but more compression time
        // Use result image to draw, image is smaller but less compression time
        [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
        resultImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        data = UIImageJPEGRepresentation(resultImage, 1);
    }
    return resultImage;
}

+ (UIImage *)imageWithMaxSide:(CGFloat)length sourceImage:(UIImage *)image
{
    CGFloat scale = [[UIScreen mainScreen] scale];
    CGSize imgSize = CWSizeReduce(image.size, length);
    UIImage *img = nil;

    UIGraphicsBeginImageContextWithOptions(imgSize, YES, scale);  // 创建一个 bitmap context

    [image drawInRect:CGRectMake(0, 0, imgSize.width, imgSize.height)
            blendMode:kCGBlendModeNormal alpha:1.0];              // 将图片绘制到当前的 context 上

    img = UIGraphicsGetImageFromCurrentImageContext();            // 从当前 context 中获取刚绘制的图片
    UIGraphicsEndImageContext();

    return img;
}


static inline
CGSize CWSizeReduce(CGSize size, CGFloat limit)   // 按比例减少尺寸
{
    CGFloat max = MAX(size.width, size.height);
    if (max < limit) {
        return size;
    }

    CGSize imgSize;
    CGFloat ratio = size.height / size.width;

    if (size.width > size.height) {
        imgSize = CGSizeMake(limit, limit*ratio);
    } else {
        imgSize = CGSizeMake(limit/ratio, limit);
    }

    return imgSize;
}

//相册新建文件夹
+ (void)createFolder:(NSString * _Nullable)videoPath mainImage:(UIImage * _Nullable)mainImage name:(NSString *)name ifPush:(BOOL)ifPush {
    if (![self isExistFolder:name]) {
        [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
            //添加HUD文件夹
            [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:name];
            
        } completionHandler:^(BOOL success, NSError * _Nullable error) {
            if (success) {
                NSLog(@"创建相册文件夹成功!");
                [self saveVideo:videoPath mainImage:mainImage name:name ifPush:ifPush];
            } else {
                NSLog(@"创建相册文件夹失败:%@", error);
            }
        }];
    }else{
        [self saveVideo:videoPath mainImage:mainImage name:name ifPush:ifPush];
    }
}


//判断相册是否有新建文件夹
+ (BOOL)isExistFolder:(NSString *)folderName {
    //首先获取用户手动创建相册的集合
    PHFetchResult *collectonResuts = [PHCollectionList fetchTopLevelUserCollectionsWithOptions:nil];
    
    __block BOOL isExisted = NO;
    //对获取到集合进行遍历
    [collectonResuts enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        PHAssetCollection *assetCollection = obj;
        //folderName是我们写入照片的相册
        if ([assetCollection.localizedTitle isEqualToString:folderName])  {
            isExisted = YES;
        }
    }];
    
    return isExisted;
}

//保存视频
+ (void)saveVideo:(NSString *_Nullable)videoUrl mainImage:(UIImage * _Nullable)mainImage name:(NSString *)name ifPush:(BOOL)ifPush{
    //标识保存到系统相册中的标识
    __block NSString *localIdentifier;
    //首先获取相册的集合
    PHFetchResult *collectonResuts = [PHCollectionList fetchTopLevelUserCollectionsWithOptions:nil];
    //对获取到集合进行遍历
    [collectonResuts enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        PHAssetCollection *assetCollection = obj;
        //folderName是我们写入照片的相册
        if ([assetCollection.localizedTitle isEqualToString:name])  {
            [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
                if (mainImage) {
                    [PHAssetChangeRequest creationRequestForAssetFromImage:mainImage];

                }else{
                    NSURL *url = [NSURL fileURLWithPath:videoUrl];
                    //请求创建一个Asset
                    PHAssetChangeRequest *assetRequest = [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:url];
                    //请求编辑相册
                    PHAssetCollectionChangeRequest *collectonRequest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:assetCollection];
                    //为Asset创建一个占位符，放到相册编辑请求中
                    PHObjectPlaceholder *placeHolder = [assetRequest placeholderForCreatedAsset];
                    //相册中添加视频
                    [collectonRequest addAssets:@[placeHolder]];
                    localIdentifier = placeHolder.localIdentifier;
                }

            } completionHandler:^(BOOL success, NSError *error) {
                if (success) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        if (ifPush) {
                            [[NSNotificationCenter defaultCenter]postNotificationName:SavePhotoVideoSucceedKey object:localIdentifier];
                        }
                        if (mainImage) {
                            [MBProgressHUD showSuccess:@"图片已保存到相册"];
                        }else{
                            [MBProgressHUD showSuccess:@"视频已保存到相册"];
                        }
                    });
                } else {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [MBProgressHUD showSuccess:@"保存到相册失败"];
                    });
                }
            }];
        }
    }];
}

///app 名字
+(NSString *)appName{
    NSString *title = [NSBundle mainBundle].infoDictionary[(__bridge NSString*)kCFBundleNameKey];
    return title;
}

///判断用户是否开启相册访问权限
+(void)canSeePhotoCompletion:(void (^_Nullable)(BOOL isSucceed, PHAuthorizationStatus photoType))completion{
    PHAuthorizationStatus oldStatus = [PHPhotoLibrary authorizationStatus];
    // 检查用户访问权限
    // 如果用户还没有做出选择，会自动弹框
    // 如果之前已经做过选择，会直接执行block
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (status == PHAuthorizationStatusDenied ) { // 用户拒绝当前App访问权限
                if (oldStatus != PHAuthorizationStatusNotDetermined) {
                    NSLog(@"提醒用户打开开关");
                }
                [[self class]showPhotoAlertView:status];
                if (completion) {
                    completion(NO,status);
                }
            } else if (status == PHAuthorizationStatusAuthorized) { // 用户允许当前App访问
                NSLog(@"可以访问");
                if (completion) {
                    completion(YES,status);
                }
            } else if (status == PHAuthorizationStatusRestricted) { // 无法访问相册
                NSLog(@"因系统原因，无法访问相册");
                [[self class]showPhotoAlertView:status];
                if (completion) {
                    completion(NO,status);
                }
            }
        });
    }];
}

///弹出设置提示
+ (void)showPhotoAlertView:(PHAuthorizationStatus)status{
    if (@available(iOS 14.0, *)) {
        if (status == PHAuthorizationStatusLimited) {
            return;
        }
    }
    NSString *contentStr = @"请在设置中为我们打开权限，以访问您的相册";
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:contentStr preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *alerOne = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {}];
    UIAlertAction *alerTwo = [UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) {}];
    }];
    [alert addAction:alerOne];
    [alert addAction:alerTwo];
    [currViewController() presentViewController:alert animated:YES completion:nil];
}

///判断当前展示的页面是不是自己
+(BOOL)isCurrentViewControllerVisible:(UIViewController *)viewController
{
    return (viewController.isViewLoaded && viewController.view.window);
}

///添加友盟统计
+(void)addUMTongJiKey:(NSString *)key subKey:(NSString *)subKey titleStr:(NSString *)titleStr{
    NSDictionary *dict = @{subKey : titleStr};
    [MobClick event:key attributes:dict];
}

/// 设置view半边圆角
/// @param corners 圆角类型
/// @param cornerRadii 圆角尺寸
/// @param subView subView
+(void)addRoundRoundingCorners:(UIRectCorner)corners cornerRadii:(CGSize)cornerRadii subView:(UIView *)subView{
    UIBezierPath *maskPath;
    maskPath = [UIBezierPath bezierPathWithRoundedRect:subView.bounds
                                     byRoundingCorners:corners
                                           cornerRadii:cornerRadii];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = subView.bounds;
    maskLayer.path = maskPath.CGPath;
    subView.layer.mask = maskLayer;
}
@end
